<template>
  <div style="width: 100%;height: 100%;">
    <div id="app" style="width: 100%;height: 100%;">
    </div>
    <!-- 全屏加载遮罩 (上传时显示) -->
    <div v-if="isUploading" class="fullscreen-loading">
      <div class="loading-spinner">
        <i class="fas fa-circle-notch fa-spin"></i>
        <div class="loading-text">正在上传... {{ uploadProgress }}%</div>
      </div>
    </div>
    <button @click="startUpload" style="position: absolute;left: 0;top: 0;z-index: 1000;">计算</button>
  </div>

</template>

<script>
import L from 'leaflet';
import html2canvas from 'html2canvas';
import axios from 'axios';

var customIcon = L.icon({
  iconUrl: 'marker.png', // 图标图片的路径
  iconSize: [32, 32], // 图标的大小
  iconAnchor: [16, 32], // 图标锚点（图标中心点相对于marker的位置）
});
let map;
export default {
  name: 'App',
  data() {
    return {
      map: null,
      imageData: '',
      points: [],
      bbox: {},
      geoJsonLayer: null,
      isUploading: false,
      uploadProgress: 0,
      markers: []
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      map = L.map('app', {
        zoomControl: false  // 关键配置：隐藏默认缩放按钮
      }).setView([34.116925383251946, 114.20569181442261], 18); // 初始中心点设为中国东部地区
      // const arcgisImageryLayer = L.tileLayer('https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png', {
      const arcgisImageryLayer = L.tileLayer('https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=fa9613cc03b449702179b0d4dd80ff55', {
        maxZoom: 18, // 最大缩放级别
      });

      // 将图层添加到地图
      arcgisImageryLayer.addTo(map);
      map.on('click', this.handleMapClick);
    },
    async handleMapClick(e) {
      this.points.push({ "lng": e.latlng.lng, "lat": e.latlng.lat })
      let marker = L.marker([e.latlng.lat, e.latlng.lng], { icon: customIcon }).addTo(map);
      this.markers.push(marker);
    },

    async startUpload() {
      for (let i = 0; i < this.markers.length; i++) {
        map.removeLayer(this.markers[i]);
      }

      let bound = map.getBounds()
      this.bbox = JSON.stringify({
        "east": bound.getEast(), "south": bound.getSouth(),
        "west": bound.getWest(),
        "north": bound.getNorth()
      })
      const mapElement = document.getElementById('app');
      // 使用html2canvas截取地图
      const canvas = await html2canvas(mapElement, {
        useCORS: true, // 处理跨域图片
        logging: false,
        scale: 0.5,
      });
      // 转换为图片URL
      this.imageData = canvas.toDataURL('image/png');
      this.upload()
    },
    async upload() {
      this.isUploading = true;
      this.uploadProgress = 0;
      const response = await fetch(this.imageData);
      const blob = await response.blob();
      // 创建FormData对象
      const formData = new FormData();
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      formData.append('image', blob, `map-screenshot-${timestamp}.png`);

      // 添加额外的坐标信息
      formData.append('points', JSON.stringify(this.points));
      formData.append('bbox', this.bbox);

      // 发送上传请求 - 请替换为您的实际上传接口URL
      axios.post('http://192.168.1.86:8001/predict', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          // 可以在这里处理上传进度
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / (progressEvent.total || 1)
          );
          this.uploadProgress = percentCompleted;
          console.log(`上传进度: ${percentCompleted}%`);
        }
      }).then(uploadResponse => {
        console.log('上传成功', uploadResponse)
        console.log('上传成功', uploadResponse);
        this.addGeojson(JSON.parse(uploadResponse.data.message))
      }).catch(err => {
        console.log('上传失败', err)
      }).finally(() => {
        this.isUploading = false;
      })

      // uploadResponse.data.message
    },
    addGeojson(data) {
      if (this.geoJsonLayer) {
        map.removeLayer(this.geoJsonLayer);
      }
      // 创建GeoJSON图层
      this.geoJsonLayer = L.geoJSON(data, {
        style: (feature) => {
          // 根据要素类型设置不同样式
          if (feature.geometry.type === 'LineString') {
            return {
              color: "#0000ff",
              weight: 3,
              opacity: 0.7
            };
          }
          if (feature.geometry.type === 'Polygon') {
            return {
              color: "#00ff00",
              weight: 2,
              fillColor: "#00ff00",
              fillOpacity: 0.3
            };
          }
          return style;
        },
        pointToLayer: (feature, latlng) => {
          // 自定义点标记
          return L.circleMarker(latlng, {
            radius: 8,
            fillColor: "#ff7800",
            color: "#ffffff",
            weight: 2,
            opacity: 1,
            fillOpacity: 0.8
          });
        },
        onEachFeature: (feature, layer) => {
          // 添加弹窗信息
          if (feature.properties && feature.properties.name) {
            layer.bindPopup(`
              <strong>${feature.properties.name}</strong><br>
              类型: ${feature.properties.type}<br>
              坐标: ${feature.geometry.coordinates.slice(0, 2).join(', ')}
            `);
          }
        }
      }).addTo(map);
    }
  }

}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

html {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

/* 全屏加载遮罩 */
.fullscreen-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(2px);
}

.loading-spinner {
  background-color: white;
  padding: 20px 30px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.loading-spinner i {
  font-size: 32px;
  color: #4285f4;
}

.loading-text {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}
</style>
